package com.aduerr.v1shouyin.mvp.fragment;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.entity.CashierPermissionEntity;
import com.aduerr.v1shouyin.entity.UserEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.activity.BangGuidActivity;
import com.aduerr.v1shouyin.mvp.activity.CalculatorActivity;
import com.aduerr.v1shouyin.mvp.activity.LoginActivity;
import com.aduerr.v1shouyin.mvp.activity.PreAuthoActivity;
import com.aduerr.v1shouyin.mvp.activity.ScanningActivity;
import com.aduerr.v1shouyin.mvp.activity.SettingActivity;
import com.aduerr.v1shouyin.mvp.activity.SignOutActivity;
import com.aduerr.v1shouyin.mvp.activity.WriteOffActivity;
import com.aduerr.v1shouyin.mvp.activity.YuShouQuanActivity;
import com.aduerr.v1shouyin.unioncard.BaseUnionFragment;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.orhanobut.hawk.Hawk;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.HashMap;

import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;


/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2018/10/15 15:31
 * @change
 * @chang time
 * @class describe
 */

public class Home2Fragment extends BaseUnionFragment {


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_2;
    }

    @Override
    protected void initBase() {
        super.initView();
    }


    @OnClick({R.id.rl_pre, R.id.rl_kaquan, R.id.rl_vip, R.id.rl_points, R.id.rl_setting
            , R.id.rl_logout, R.id.rl_cash_pay, R.id.rl_scan_pre})
    void clicked(View v) {
        switch(v.getId()) {
            case R.id.rl_pre:
                if(Hawk.get("f_pre") == null) {
                    Hawk.put("f_pre", 1);
                } else {
                    Hawk.put("f_pre", (int) Hawk.get("f_pre") + 1);
                }
                startActivity(new Intent(mContext, YuShouQuanActivity.class));
                break;
            case R.id.rl_vip:
                if(Hawk.get("f_vip") == null) {
                    Hawk.put("f_vip", 1);
                } else {
                    Hawk.put("f_vip", (int) Hawk.get("f_vip") + 1);
                }
                Intent intent1 = new Intent(mContext, ScanningActivity.class);
                intent1.putExtra(Constants.QRCODE_CAPUTER, Constants.MEMBER_RECHARGE_QR);
                intent1.putExtra("beizhu", "");
                startActivity(intent1);
                break;
            case R.id.rl_kaquan:
                if(Hawk.get("f_kaquan") == null) {
                    Hawk.put("f_kaquan", 1);
                } else {
                    Hawk.put("f_kaquan", (int) Hawk.get("f_kaquan") + 1);
                }
                startActivity(new Intent(mContext, WriteOffActivity.class));
                break;
            case R.id.rl_points:
                if(Hawk.get("f_points") == null) {
                    Hawk.put("f_points", 1);
                } else {
                    Hawk.put("f_points", (int) Hawk.get("f_points") + 1);
                }
                Intent intent2 = new Intent(mContext, ScanningActivity.class);
                intent2.putExtra(Constants.QRCODE_CAPUTER,
                        Constants.MEMBER_SCANCODEJIFEN_QR);
                intent2.putExtra("beizhu", "");
                startActivity(intent2);
                break;
            case R.id.rl_setting:
                if(Hawk.get("f_setting") == null) {
                    Hawk.put("f_setting", 1);
                } else {
                    Hawk.put("f_setting", (int) Hawk.get("f_setting") + 1);
                }
                startActivity(new Intent(mContext, SettingActivity.class));
                break;
            case R.id.rl_logout:
                if(Hawk.get("f_logout") == null) {
                    Hawk.put("f_logout", 1);
                } else {
                    Hawk.put("f_logout", (int) Hawk.get("f_logout") + 1);
                }

                boolean hasShiftDuty =
                        (Boolean) SharedPreferencesUtils.getParam(mContext,
                                "hasShiftDuty", true);
                if(hasShiftDuty) {
                    String userLevel = Hawk.get("level");
                    if(userLevel.equals("收银员")) {
                        checkCashierPermission();
                    } else {
                        startActivity(new Intent(mContext, SignOutActivity.class));
                    }
                } else {
                    postNetforLogin(Hawk.get("userName"), Hawk.get("password"));
                }
                break;
            case R.id.rl_cash_pay:
                Intent intent = new Intent(mContext, CalculatorActivity.class);
                intent.putExtra("CSAH_TYPE", CalculatorActivity.CASH);
                startActivity(intent);
                break;
            case R.id.rl_scan_pre:
                startActivity(new Intent(mContext, PreAuthoActivity.class));
                break;

        }
    }


    /**
     * 请求成功=1
     * 签名无效=-1
     * 密码错误=-2
     * 用户不存在=-3
     * 异常错误=-4
     * 用户已暂停使用=-6
     * 设置未注册=-100
     * 设备未绑定=-200
     * 登陆信息错误=-300
     */
    private void postNetforLogin(String account, String password_content) {
//        ToastUtils.showToast(this, "登录结果展示");
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("userName", "" + account);
        addParams.put("password", "" + password_content);
        addParams.put("logType", "1");
        APIRetrofit.getAPIService().Signout(RXRequest.getXingPosParams(addParams,
                mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<UserEntity>() {
                    @Override
                    public void onNext(UserEntity userEntity) {
                        //                    if (Tools.isAvailable(userEntity))return;
                        int success = userEntity.getSuccess();
                        if(success == 1) {
                            //将数据存入数据库
                            SharedPreferencesUtils.remove(mContext, "autologin");
                            SharedPreferencesUtils.remove(mContext, "remberpassword");
                            //将极光推送的别名重置.
                            JPushInterface.setAlias(App.getApp(), "",
                                    (i, s, set) -> Log.d("alias",
                                            "set alias result is" + i));
                            Intent intent = new Intent(mContext, LoginActivity.class);
                            startActivity(intent);
                            getActivity().finish();
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(mContext, "autologin");
                            SharedPreferencesUtils.remove(mContext, "remberpassword");
                            startActivity(new Intent(mContext, BangGuidActivity.class));
                            getActivity().finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            SharedPreferencesUtils.remove(mContext, "autologin");
                            SharedPreferencesUtils.remove(mContext, "remberpassword");
                            startActivity(new Intent(mContext, LoginActivity.class));
                            getActivity().finish();
                        } else {
                            ToastUtils.showToast(mContext, userEntity.getErrMsg() + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(App.getApp(), "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(App.getApp(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(App.getApp(), "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    /**
     * 作用：获取收银员是否有查看对账权限
     * 说明：收银员查看对账权限不宜放在登录里因为后台随时可能更改权限，故每次点击都请求，默认没权限
     */
    public void checkCashierPermission() {
        HashMap<String, String> addParams = new HashMap<>();
        APIRetrofit.getAPIService().isCashierCanCheckBill(RXRequest.getXingPosParams(addParams, mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CashierPermissionEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CashierPermissionEntity entity) {
                        if(entity.getSuccess() == 1) {
                            boolean b = entity.isIsLookSummaryData();
                            if(b){
                                startActivity(new Intent(mContext, SignOutActivity.class));
                            }else{
                                postNetforLogin(Hawk.get("userName"), Hawk.get("password"));
                            }
                        } else {
                            com.blankj.utilcode.util.ToastUtils.showShort(entity.getErrMsg() + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
